import Taro from '@tarojs/taro'
import { Current } from '@tarojs/taro'
import React, { PureComponent } from 'react'
// 界面组件
import { View, Text } from '@tarojs/components'
import { AtList, AtListItem, AtFloatLayout, AtInput, AtButton, AtInputNumber } from 'taro-ui'
import CTopbar from '../../components/CTopbar/index'
import CCollegeMoreCard from '../../components/CCollegeMoreCard/index'
import CHomeMoreCard from '../../components/CHomeMoreCard/index'
import { get_data_api, addOrder_api, pay_api } from './service'
import './index.scss'
import GetTopBarInfo from '@/utils/GetTopBarInfo' //动态高度
import CCourseCard from '@/components/CCourseCard'
/**
 * 订单支付页
 */
type I = {
  data: any
  type: number
  id: number
  tabstatus: string
  success: boolean
  isOpened: boolean
  orderId: number
  name: string
  phone: string
  extraText: string
  value: number
  system: string
}
interface Pay {
  state: I
}
class Pay extends PureComponent<any> {
  constructor(props) {
    super(props)
    this.state = {
      data: {},
      type: 0,
      id: 0,
      tabstatus: '',
      success: false,
      isOpened: false,
      orderId: 0,
      name: '',
      phone: '',
      extraText: '获取更优质的服务', //填写的信息展示使用
      value: 1,
      system: Taro.getStorageSync('system') || '',
    }
  }
  componentDidMount() {
    // type: 1:测评 2：课程   3线下课程
    // tabstatus  切换栏 类型 0 ，1 ， 2
    const { type, id, orderId } = Current.router?.params
    this.setState(
      {
        type: Number(type),
        id: Number(id),
        orderId: Number(orderId),
      },
      () => {
        this.get_data()
      },
    )
    // if (orderId) {
    //   this.get_order(orderId)
    // } else {
    //   this.get_data(Number(id), Number(type))
    // }
  }
  // 获取订单信息
  // get_order(orderId) {
  //   get_goods_api(orderId).then(({ result, data }) => {
  //     console.log(data)
  //   })
  // }

  // 获取商品信息
  get_data() {
    const { id, type } = this.state
    get_data_api(id, type).then(({ result, data }) => {
      this.setState({
        data,
        success: true,
      })
    })
  }
  // 下单 去支付
  async to_pay() {
    const { type, id, data, orderId } = this.state
    if (!id) {
      Taro.showToast({
        title: '请稍后再试！',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    // 线下课程需要验证个人信息
    if (type === 4 && !this.saveChange()) {
      return
    }

    const sysinfo = Taro.getSystemInfoSync()
    if (sysinfo.system.indexOf('iOS') < 0) {
      this.setState(
        {
          orderId,
        },
        () => {
          this.pay()
        },
      )
    } else {
      Taro.showModal({
        title: '提示',
        content: '十分抱歉，由于相关规范，您暂时无法测试',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        },
      })
    }
  }

  async pay() {
    await this.addOrder()
    const { type, id, orderId } = this.state
    const params = this.state.data
    if (!orderId) {
      Taro.showToast({
        title: '请稍后再试！',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    await pay_api(orderId).then(({ result, data }) => {
      if (result === 1999) {
        Taro.requestPayment({
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: data.signType,
          paySign: data.paySign,
          success: function (res) {
            Taro.showLoading({
              title: '请稍等',
              mask: true,
              success: () => {
                setTimeout(() => {
                  Taro.redirectTo({
                    url:
                      '/pages/PaymentResults/index?orderType=' +
                      type +
                      '&id=' +
                      id +
                      '&price=' +
                      params.price +
                      '&isErr=' +
                      // 0支付成功 1支付失败
                      (res.errMsg === 'requestPayment:ok' ? 0 : 1),
                  })
                  Taro.hideLoading()
                }, 2000)
              },
            })
          },
          fail: function (res) {
            console.log(res)
          },
        })
      }
    })
  }

  saveChange() {
    const { name, phone } = this.state
    var phoneReg = /(^1[3|4|5|7|8|9]\d{9}$)|(^09\d{8}$)/
    var nameReg = /^[\u4E00-\u9FA5]{2,4}$/
    if (!nameReg.test(name)) {
      Taro.showToast({
        title: '请输入正确姓名',
        icon: 'none',
        duration: 2000,
        mask: true,
      })
      return false
    }
    if (!phoneReg.test(phone)) {
      Taro.showToast({
        title: '请输入正确手机号码',
        icon: 'none',
        duration: 2000,
        mask: true,
      })
      return false
    }
    this.setState({
      isOpened: false,
      extraText: name + '——' + phone,
    })
    // this.addOrder()
    return true
  }

  async addOrder() {
    const { name, phone, id, type, value } = this.state
    const params = {
      // price: data.price,
      // actualPrice: data.price,
      commodityId: id,
      commodityType: type,
      appointmentName: name,
      appointmentPhone: phone,
      commodityNumber: value, //数量
    }
    await addOrder_api(params).then(({ result, data }) => {
      this.setState({
        orderId: data,
      })
    })
  }
  changeListItem() {
    this.setState({
      isOpened: true,
    })
  }
  handleClose() {
    this.setState({
      isOpened: false,
    })
  }
  handlePhoneChange(e) {
    this.setState({
      phone: e,
    })
  }
  handleNameChange(e) {
    this.setState({
      name: e,
    })
  }
  handleInputNumberChange(value) {
    this.setState({
      value,
    })
  }
  render() {
    // type  1-> 测试题 2->课程 3-> 预约 4->线下课程
    const { type = 0, id = '', data, success, isOpened, name, phone, extraText, value, system } = this.state
    return (
      <View style={{ paddingTop: `${GetTopBarInfo().TopBarHeight}px` }}>
        <View className='header'>
          <CTopbar title='支付' showBack></CTopbar>
        </View>
        <View className='content'>
          {success && type === 1 ? (
            <CHomeMoreCard
              img={data.questionImg}
              title={data.questionName}
              price={data.price}
              subTitle={data.questionSubtitle}
              personNum={data.questionNumber}
              type={1}
            />
          ) : success && type === 2 ? (
            <CCollegeMoreCard data={success && data} />
          ) : (
            <CCourseCard data={success && data} />
          )}

          {/* <CConsultingCard /> */}
        </View>
        <View className='number'>
          <View>数量：</View>
          <AtInputNumber type='number' min={0} max={10} step={1} value={value} onChange={this.handleInputNumberChange.bind(this)} />
        </View>
        <View>
          {type === 4 ? (
            <View className='strip'>
              <AtList>
                <AtListItem arrow='right' title='资讯信息' extraText={extraText} onClick={this.changeListItem.bind(this)} />
              </AtList>
            </View>
          ) : (
            ''
          )}
        </View>
        <AtFloatLayout isOpened={isOpened} title='填写资料' onClose={this.handleClose.bind(this)}>
          <View className='input_wrapper'>
            <AtInput
              required
              name='name'
              title='姓名'
              type='text'
              placeholder='请输入咨询人姓名'
              value={name}
              onChange={this.handleNameChange.bind(this)}
            />
            <AtInput
              required
              name='phone'
              title='手机号'
              type='text'
              placeholder='请输入咨询电话'
              value={phone}
              onChange={this.handlePhoneChange.bind(this)}
            />
            <View className='save' style={{ margin: '30px 0' }}>
              <AtButton circle type='primary' onClick={this.saveChange.bind(this)}>
                保存
              </AtButton>
            </View>
          </View>
        </AtFloatLayout>
        <View className='Payfooter'>
          <View className='Payfooter_left'>
            <Text>合计金额</Text>
            <Text className='Payfooter_price'>
              {system.indexOf('iOS') < 0 ? (success && data.price ? '￥' + data.price : '免费') : '免费'}
            </Text>
          </View>
          <View className='Payfooter_right' onClick={this.to_pay.bind(this)}>
            <Text>去支付</Text>
          </View>
        </View>
      </View>
    )
  }
}

export default Pay
